import 'dart:convert';
import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_pack_up_keyboard_widget/common_pack_up_keyboard_widget.dart';
import 'package:e_reception_flutter/singleton/amap_repository/amap_repository.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/bind_terminal_info_confirm_page.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/binding_terminal_view_model.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/event/terminal_info_update_event.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/terminal_detail_info_page.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/terminal_pic_detail_page.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/event/terminal_auto_on_off_refresh_event.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/search_terminal_list_page.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/terminal_common_settings_page.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/terminal_scan_page.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/utils/utils.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_location_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/mixin/vg_place_holder_status_mixin.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_pull_to_refresh_widget/vg_pull_to_refresh_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:matisse_android_plugin/export_matisse.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import '../../app_main.dart';
import '../set_terminal_status_menu_dialog.dart';
import 'bean/new_terminal_response_bean.dart';
import 'bean/set_terminal_state_type.dart';
import 'event/terminal_list_refresh_event.dart';
import 'new_terminal_list_view_model.dart';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:vg_base/vg_permission_lib.dart';

/// 新终端列表
///
/// @author: zengxiangxi
/// @createTime: 1/6/21 11:03 AM
/// @specialDemand:
class NewTerminalListPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "NewTerminalListPage";
  final String gps;

  const NewTerminalListPage({Key key,this.gps,}):super(key: key);

  @override
  _NewTerminalListPageState createState() => _NewTerminalListPageState();

  ///跳转方法
  static Future<dynamic> navigatorPush(BuildContext context, {String gps}) {
    return RouterUtils.routeForFutureResult(
      context,
      NewTerminalListPage(
        gps:gps,
      ),
      routeName: NewTerminalListPage.ROUTER,
    );
  }
}

class _NewTerminalListPageState
    extends BasePagerState<NewTerminalListItemBean, NewTerminalListPage>
    with VgPlaceHolderStatusMixin {
  NewTerminalListViewModel _viewModel;
  BindingTerminalViewModel _bindingViewModel;

  String _searchStr;
  String _gps;
  @override
  void initState() {
    super.initState();
    _gps = widget?.gps??"";
    _viewModel = NewTerminalListViewModel(this, allflg: "01", searchStrFunc: () => _searchStr, gps: _gps);
    _viewModel.refresh();
    VgLocation().requestSingleLocation((value) {
      Future<String> latlng = VgLocationUtils.getCacheLatLngString();
      latlng.then((value){
        if(value == _gps){
          print("当前使用的gps与最新的一致，不需要再次刷新");
          return;
        }
        _gps = value;
        _viewModel = NewTerminalListViewModel(this, searchStrFunc: () => _searchStr, gps: _gps);
        _viewModel.refresh();
      });
    });
    _bindingViewModel = BindingTerminalViewModel(this);
    VgEventBus.global.on().listen((event) {
      if(event is TerminalListRefreshEvent
          || event is TerminalAutoOnOffRefreshEvent){
        _viewModel.refresh();
      }
      if(event is TerminalInfoUpdateEvent && "通用设置更新" == event.message){
        _viewModel.refresh();
      }
    });
    initCache();
  }

  void initCache() async {
    String jsonStr = await SharePreferenceUtil.getString(NewTerminalListUtils.getTerminalListCacheKey());
    if(StringUtils.isEmpty(jsonStr)) return;
    try {
      List list = json.decode(jsonStr);
      List<NewTerminalListItemBean> records = list.map((e) => NewTerminalListItemBean.fromMap(e)).toList();
      if(records?.isEmpty ?? true) return;
      data = records;
      setState(() { });
    } catch (e) {}
  }
  @override
  Widget build(BuildContext context) {
    return _toScaffoldWidget();
  }

  Widget _toScaffoldWidget() {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      resizeToAvoidBottomPadding: false,
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      body: CommonPackUpKeyboardWidget(child: _toMainColumnWidget()),
    );
  }

  Widget _toMainColumnWidget() {
    return Column(
      children: <Widget>[
        _toTopBarWidget(),
        _toCommonSettingsWidget(),
        // SizedBox(height: 14),
        Expanded(
            child: VgPlaceHolderStatusWidget(
              errorOnClick: () => _viewModel?.refresh(),
              emptyOnClick: () => _viewModel?.refresh(),
              loadingStatus: data == null,
              child: _toListParentWidget(),
              // NestedScrollView(
              //     headerSliverBuilder: (context, bool) {
              //       return [
              //         SliverPersistentHeader(
              //           delegate: CommonSliverPersistentHeaderDelegate(
              //             minHeight: 50,
              //             maxHeight: 50,
              //             child: Container(
              //               color: ThemeRepository.getInstance()
              //                   .getCardBgColor_21263C(),
              //               padding: EdgeInsets.symmetric(vertical: 10),
              //               child:CommonSearchBarWidget(
              //                 hintText: "搜索名字",
              //                 // onChanged: (String searchStr) => _searchStr = searchStr,
              //                 onSubmitted: (String searchStr) {
              //                   _searchStr = searchStr;
              //                   _viewModel?.refreshMultiPage();
              //                 },
              //               ),
              //             ),
              //           ),
              //         ),
              //       ];
              //     },
              //     body: _toListParentWidget()
              // )
            )),
      ],
    );
  }

  Widget _toListParentWidget() {
    return VgPullRefreshWidget.bind(
        state: this,
        viewModel: _viewModel,
        child: _toListWidget());
  }

  Widget _toListWidget() {
    return ListView.separated(
        itemCount: data?.length ?? 0,
        padding: const EdgeInsets.all(0),
        physics: BouncingScrollPhysics(),
        keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
        itemBuilder: (BuildContext context, int index) {
          return _toListItemWidget(context, index, data?.elementAt(index));
        },
        separatorBuilder: (BuildContext context, int index) {
          return SizedBox(height: 0);
        });
  }

  ///列表项
  Widget _toListItemWidget(
      BuildContext context, int index, NewTerminalListItemBean itemBean) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () async {
        if (StringUtils.isEmpty(itemBean?.hsn)) {
          VgToastUtils.toast(AppMain.context, "终端获取异常");
          return;
        }
        dynamic result;
        if(itemBean?.bindflg == "00"){
          result = await BindTerminalInfoConfirmPage.navigatorPush(context, itemBean?.hsn);
          if(result == null){
            _bindingViewModel.exitBindTerminal(itemBean?.hsn);
          }
        }else{
          result = await TerminalDetailInfoPage.navigatorPush(context, itemBean?.hsn, terminalCount: data?.length??0, router: NewTerminalListPage.ROUTER);
          _viewModel?.refreshMultiPage();
        }

        if (result is bool && result ) {
          _viewModel?.refreshMultiPage();
        }
      },
      child: Container(
        height: 102,
        child: Row(
          children: <Widget>[
            SizedBox(
              width: 15,
            ),
            GestureDetector(
              behavior: HitTestBehavior.translucent,
              onTap: () => StringUtils.isEmpty(itemBean?.terminalPicurl ?? "")
                  ?_chooseSinglePicAndClip(itemBean)
                  :TerminalPicDetailPage.navigatorPush(context,
                  url: itemBean?.terminalPicurl,
                  selectMode: SelectMode.Normal,
                  clipCompleteCallback: (path, cancelLoadingCallback) {
                    itemBean?.terminalPicurl = path;
                    setState(() {});
                    _bindingViewModel.setTerminalPic(context, itemBean?.id, itemBean?.hsn,
                        "01", itemBean?.terminalPicurl);
                  }),
              child: ClipRRect(
                  borderRadius: BorderRadius.circular(4),
                  child: Container(
                    width: 78,
                    height: 78,
                    color: Color(0xFF191E31),
                    child: VgCacheNetWorkImage(
                      itemBean?.terminalPicurl ?? "",
                      defaultErrorType: ImageErrorType.head,
                      errorWidget: Container(
                        child: Image.asset(
                          "images/icon_terminal_holder.png",
                          fit: BoxFit.cover,
                        ),
                      ),
                      placeWidget: Container(
                        child: Image.asset(
                          "images/termial_empty_place_holder_ico.png",
                          fit: BoxFit.cover,
                        ),
                      ),
                    ),
                  )),
            ),
            Expanded(child: _toContentWidget(context, index, itemBean)),
            // _toButtonStatusWidget(itemBean),
          ],
        ),
      ),
    );
  }

  void _chooseSinglePicAndClip(NewTerminalListItemBean itemBean) async {
    String fileUrl =
    await MatisseUtil.clipOneImage(context, scaleX: 1, scaleY: 1,
        onRequestPermission: (msg)async{
          bool result =
          await CommonConfirmCancelDialog.navigatorPushDialog(context,
            title: "提示",
            content: msg,
            cancelText: "取消",
            confirmText: "去授权",
          );
          if (result ?? false) {
            PermissionUtil.openAppSettings();
          }
        });
    if (fileUrl == null || fileUrl == "") {
      return null;
    }
    itemBean?.terminalPicurl = fileUrl;
    setState(() {});
    _bindingViewModel.setTerminalPic(context, itemBean?.id, itemBean?.hsn,
        "01", itemBean?.terminalPicurl);
  }

  Widget _toContentWidget(context, int index, NewTerminalListItemBean itemBean) {
    SetTerminalStateType currentType = itemBean.getTerminalState();
    return Container(
      margin: const EdgeInsets.only(left: 12),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Row(
            children: <Widget>[
              Visibility(
                visible: (StringUtils.isEmpty(itemBean?.terminalName) && StringUtils.isEmpty(itemBean?.sideNumber)&& StringUtils.isNotEmpty(itemBean?.hsn)),
                child: Text(
                  // "硬件ID：",
                  "",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 15,
                    // fontWeight: FontWeight.w600
                  ),
                ),
              ),
              Expanded(
                child: Text(
                  itemBean?.getTerminalName(index),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 15,
                    // fontWeight: FontWeight.w600
                  ),
                ),
              ),
              GestureDetector(
                behavior: HitTestBehavior.translucent,
                onTapUp: (detail){
                  // if(itemBean?.getTerminalIsOff()??true){
                  //   return;
                  // }
                  SetTerminalStatusMenuDialog.navigatorPushDialog(context,
                        (currentState){
                      _onOpen?.call(currentState, itemBean?.hsn);
                    },
                        (currentState){
                      _screenOff?.call(currentState, itemBean?.hsn);
                    },
                        (currentState){
                      _off?.call(currentState, itemBean?.hsn);
                    },
                        (time){

                    },
                    itemBean?.getTerminalState(),
                    itemBean?.autoOnoffTime??"",
                    itemBean?.autoOnoffWeek??"",
                    itemBean.hsn,
                    itemBean.id,
                    itemBean?.getTerminalName(index),
                    itemBean?.autoOnoff,
                    itemBean?.comAutoSwitch,
                  );
                  // TerminalStateMenuDialogUtils.showMenuDialog(
                  //     context: context,
                  //     tabUpDetails: detail,
                  //     itemMap: _getMenuMap(context, itemBean),
                  //     sortType: currentType
                  // );
                },
                child: Container(
                  alignment: Alignment.centerRight,
                  padding: EdgeInsets.symmetric(horizontal: 15),
                  child: Row(
                    children: [
                      // SizedBox(width: 20,),
                      Container(
                        alignment: Alignment.centerRight,
                        // width: 80,
                        padding: EdgeInsets.symmetric(vertical: 2.5),
                        child: Text(
                          itemBean.getTerminalStateString(),
                          style: TextStyle(
                            fontSize: 12,
                            color: (itemBean?.getTerminalIsOff()??true)
                                ?ThemeRepository.getInstance().getDefaultGrayColor_FF5E687C()
                                :ThemeRepository.getInstance().getHintGreenColor_00C6C4(),
                          ),
                        ),
                      ),
                      Row(
                        children: [
                          SizedBox(width: 5,),
                          Image(
                            image: AssetImage("images/icon_shape_arrow_down.png"),
                            width: 7,
                          ),
                        ],
                      ),

                    ],
                  ),
                ),
              ),
            ],
          ),
          SizedBox(
            height: 2,
          ),
          Container(
            margin: const EdgeInsets.only(right: 12),
            child: Text(
              showOriginEmptyStr(itemBean?.position) ?? itemBean?.address ?? "",
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                color: VgColors.INPUT_BG_COLOR,
                fontSize: 12,
              ),
            ),
          ),
          SizedBox(
            height: 2,
          ),
          Text(
            "管理员：${itemBean?.manager ?? "-"}${_getLoginStr(itemBean?.loginName) ?? ""}",
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              color: VgColors.INPUT_BG_COLOR,
              fontSize: 12,
            ),
          ),
          SizedBox(
            height: 3,
          ),
          _toAccountStatus(itemBean),
        ],
      ),
    );
  }

  Widget _toAccountStatus(NewTerminalListItemBean itemBean){
    return (StringUtils.isNotEmpty(itemBean?.appedition)?itemBean.isShowEndDay():
    UserRepository.getInstance().userData.companyInfo.isShowEndDay())?
    Row(
      children: [
        Text(
          "账号状态：",
          style: TextStyle(
              color: VgColors.INPUT_BG_COLOR,
              fontSize: 12,
              height: 1.22
          ),
        ),
        Text(
          itemBean.getEndDayString(),
          style: TextStyle(
              color: VgColors.INPUT_BG_COLOR,
              fontSize: 12,
              height: 1.2
          ),
        ),
        Text(
          itemBean.getNotifyString(),
          style: TextStyle(
              color: ThemeRepository.getInstance().getMinorRedColor_F95355(),
              fontSize: 12,
              height: 1.2
          ),
        ),
      ],
    )
        :Text(
      "账号状态：长期有效",
      style: TextStyle(
          color: VgColors.INPUT_BG_COLOR,
          fontSize: 12,
          height: 1.22
      ),
    );
  }

  void _onOpen(SetTerminalStateType currentState, String hsn){
    print("开机");
    _viewModel.terminalOffScreen(context, hsn, "00", callback: (){
    });
  }

  void _screenOff(SetTerminalStateType currentState, String hsn){
    print("息屏开机");
    _viewModel.terminalOffScreen(context, hsn, "01", callback: (){
    });
  }

  void _off(SetTerminalStateType currentState, String hsn){
    print("关机");
    _viewModel.terminalOff(context, hsn, callback: (){
    });
  }

  // void _onOpen(NewTerminalListItemBean itemBean){
  //   print("开机");
  //   if("00" == itemBean.screenStatus){
  //     return;
  //   }
  //   _viewModel.terminalOffScreen(context, itemBean?.hsn, "00");
  // }
  //
  // void _screenOff(NewTerminalListItemBean itemBean){
  //   print("息屏开机");
  //   if("01" == itemBean.screenStatus){
  //     return;
  //   }
  //   _viewModel.terminalOffScreen(context, itemBean?.hsn, "01");
  // }
  //
  // void _off(NewTerminalListItemBean itemBean){
  //   print("关机");
  //   _viewModel.terminalOff(context, itemBean?.hsn);
  // }

  // Map<SetTerminalStateType,ValueChanged> _getMenuMap(BuildContext context, NewTerminalListItemBean itemBean){
  //   //开机状态，
  //   if(itemBean.onOff == 1){
  //     return {
  //       SetTerminalStateType.open:(_){
  //         _onOpen?.call(itemBean);
  //       },
  //       SetTerminalStateType.screenOff:(_){
  //         _screenOff?.call(itemBean);
  //       },
  //       SetTerminalStateType.off:(_){
  //         _off?.call(itemBean);
  //       },
  //     };
  //   }
  //
  // }

  String _getLoginStr(String loginName) {
    if (loginName == null || loginName == "") {
      return null;
    }
    return "（$loginName账号登录）";
  }

  Widget _toButtonStatusWidget(NewTerminalListItemBean itemBean) {
    if (!(itemBean?.bindflg == "00")) {
      // return SizedBox(
      //   width: 15,
      // );
    }
    return Offstage(
      offstage: !(itemBean?.bindflg == "00"),
      child: Container(
        width: 90,
        child: _toBindButtonWidget(itemBean),
      ),
    );
  }

  Widget _toBindButtonWidget(NewTerminalListItemBean itemBean) {
    return Align(
      alignment: Alignment.topCenter,
      child: Builder(
        builder: (BuildContext context) => Container(
          width: 60,
          height: 28,
          margin: const EdgeInsets.symmetric(vertical: 12),
          decoration: BoxDecoration(
              color: ThemeRepository.getInstance().getMinorRedColor_F95355(),
              borderRadius: BorderRadius.circular(14)),
          child: Center(
            child: Text(
              "绑定",
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(color: Colors.white, fontSize: 13, height: 1.2),
            ),
          ),
        ),
      ),
    );
  }


  ///topbar
  Widget _toTopBarWidget() {
    return ValueListenableBuilder(
      valueListenable: _viewModel?.totalValueNotifier,
      builder: (BuildContext context, int total, Widget child) {
        return VgTopBarWidget(
          title: "终端显示屏·${total ?? 0}",
          isShowBack: true,
          rightPadding: 0,
          rightWidget: Row(
            children: [
              GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {
                  //主页面搜索按钮
                  SearchTerminalListPage.navigatorPush(context, _gps);
                },
                child: Container(
                    height: 28,
                    padding: const EdgeInsets.only(left: 15, right: 10),
                    child: Center(
                      child: Image.asset(
                        "images/common_search_ico.png",
                        color: Colors.white,
                        width: 20,
                      ),
                    )),
              ),
              GestureDetector(
                behavior: HitTestBehavior.translucent,
                onTap: () async{
                  bool result = await TerminalScanPage.navigatorPush(context,_gps, NewTerminalListPage.ROUTER);
                  if(result != null){
                    _viewModel.refresh();
                  }
                },
                child: Container(
                  padding: EdgeInsets.only(top: 10, bottom: 10, left:15, right: 15),
                  alignment: Alignment.center,
                  child: Image.asset(
                    "images/icon_scan_code.png",
                    width: 20,
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _toCommonSettingsWidget(){
    return ValueListenableBuilder(
      valueListenable: _viewModel?.totalValueNotifier,
      builder: (BuildContext context, int total, Widget child) {
        return GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: (){
            TerminalCommonSettingsPage.navigatorPush(context);
          },
          child: Visibility(
            visible: (total??0)>1,
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 15),
              alignment: Alignment.center,
              height: 40,
              color: Color(0X141890FF),
              child: Row(
                children: [
                  Text(
                    "通用设置·共${total??0}台设备",
                    style: TextStyle(
                        fontSize: 14,
                        height: 1.2,
                        color: ThemeRepository.getInstance().getPrimaryColor_1890FF()
                    ),
                  ),
                  Spacer(),
                  Image.asset(
                    "images/index_arrow_ico.png",
                    width: 6,
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }
}
